<template>
  <div style="width: 100%; margin-top: 30px; height: 600px">
    <el-button
      type="primary"
      v-if="tableData && tableData.length > 0"
      :disabled="selectData.length < 1"
      @click="toExportFile"
      >导出文件</el-button
    >
    <el-table
      border
      show-summary
      :summary-method="getSummaries"
      :data="tableData"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" label="序号" />
      <el-table-column prop="购买方名称" label="购买方名称" />
      <el-table-column prop="货物或应税劳务名称" label="货物或应税劳务名称" />
      <el-table-column prop="单位" label="单位" />
      <el-table-column prop="单价" label="单价" />
      <el-table-column prop="orderNum" label="数量" />
      <el-table-column prop="jine" label="金额"> </el-table-column>
      <!-- <el-table-column prop="数量"
                       label="数量" /> -->
      <el-table-column prop="价税合计"
                       label="价税合计" />
      <el-table-column prop="plateNumber" label="车牌号" />
      <el-table-column prop="name" label="司机" />
      <el-table-column prop="phone" label="手机号" />

      <el-table-column prop="time" label="发货日期" />
      <el-table-column>
        <template #default="scope">
          <el-button @click="printOrder(scope.row)">打印</el-button>
        </template>
      </el-table-column>
    </el-table>
    <InvoiceDialog ref="printOrederRef"></InvoiceDialog>
  </div>
</template>

<script setup lang="ts">
import InvoiceDialog from "./InvoiceDialog.vue";
import { dayjs } from "element-plus";

let printOrederRef = ref();
/**
 * 打印预览发货单
 */
const printOrder = (val: any) => {
  printOrederRef.value.init([val]);
};

import {
  getRandomCar,
  getDatesByMonthAndYear,
  splitTotal,
  selectRandom,
  selectRandom1,
  splitNumberRandomly
} from "../utils";
import { ElMessage } from "element-plus";
let orginData: any = ref([]); //原始数据
let tableData: any = ref([]);
const route = useRoute();
console.log("selectData:", JSON.parse(route.query.selectData as any));
/*************************** 接收数据处理 *************************************/
//接收数据
orginData.value = JSON.parse(route.query.selectData as any);
//车辆限制
const carWeight = [13000, 26000,23740, 22600, 15200, 12000, 14000,13350,13010,11060,12039,9060,9450,7045,7640,13840,13530];
//拆分数据
const splitData = () => {
  let randomArray = Array.from({length: 500}, () => Math.floor(Math.random() * (20001 - 7000) + 7000))

  orginData.value.forEach((item: any) => {
    let result = selectRandom1();
    console.log("result:", result);

    let data = splitTotal(item.数量, randomArray);
    // let data = splitNumberRandomly(item.数量, 7000,result);
    if (data && data.length > 0) {
      data.forEach((orderItem:any) => {
        const carInfo = getRandomCar();
        tableData.value.push({
          购买方名称: item.购买方名称,
          货物或应税劳务名称: item.货物或应税劳务名称,
          单位: item.单位,
          单价: Number(item.单价*1.13).toFixed(4),
          数量: item.数量,
          价税合计: item.价税合计,
          orderNum: orderItem,
          plateNumber: carInfo.plateNumber,
          name: carInfo.name,
          phone: carInfo.phone,
          jine: Number(
            Number(Number(orderItem) * Number(item.单价)*1.13).toFixed(2)
          ),
        });
      });
    }
  });
  //获取第一个月份
  const currentDate = dayjs(orginData.value[0].开票日期);
  const year = currentDate.year();
  const month = currentDate.month() + 1; // month()方法返回的是0-11，所以需要加1
  console.log(tableData.value.length);
  const dayList = getDatesByMonthAndYear(year, month, tableData.value.length);
  tableData.value.forEach((item: any, index: number) => {
    item.time = dayList[index];
  });
};

const getSummaries = (param: SummaryMethodProps) => {
  const { columns, data } = param;
  const sums: string[] = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (
      !values.every((value) => Number.isNaN(value)) &&
      (index === 4 || index === 5)
    ) {
      sums[index] = `${values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return prev + curr;
        } else {
          return prev;
        }
      }, 0)}`;
    } else {
      sums[index] = "N/A";
    }
  });

  return sums;
};
splitData();
/*************************** 打印数据 *************************************/
// 批量打印
const toPrintMany = () => {
  printOrederRef.value.init([...selectData.value]);
};
/*************************** 导出数据 *************************************/
//选中的数据
let selectData: any = ref([]);
/**
 * 选择多个
 * @param val
 */
const handleSelectionChange = (val: any) => {
  console.log("多个数据：", val);
  selectData.value = val;
};

/**
 * 导出数据
 */
import * as XLSX from "xlsx";
const toExportFile = () => {
  if (selectData.value.length <= 0) {
    ElMessage.warning("请选择数据！");
    return false;
  }
  let tableData = [
    [
      "序号",
      "购买方名称",
      "货物或应税劳务名称",
      "单位",
      "单价",
      "orderNum",
      "jine",
      "plateNumber",
      "name",
      "phone",
      "time",
    ], //导出表头
  ]; // 表格表头
  selectData.value.forEach((item: any, index: number) => {
    let rowData = [];
    //导出内容的字段
    rowData = [
      index + 1,
      item.购买方名称,
      item.货物或应税劳务名称,
      item.单位,
      item.单价,
      item.orderNum,
      item.jine,
      item.plateNumber,
      item.name,
      item.phone,
      item.time,
    ];
    tableData.push(rowData);
  });
  let workSheet = XLSX.utils.aoa_to_sheet(tableData);
  let bookNew = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(bookNew, workSheet, "作品名称"); // 工作簿名称
  let currentTimestampInSeconds = Date.now();
  let name = "发货单" + currentTimestampInSeconds + ".xlsx";
  XLSX.writeFile(bookNew, name);
};
const toExportAllFile = () => {
  if (orginData.value.length <= 0) {
    ElMessage.warning("请选择数据！");
    return false;
  }
  let tableData = [
    [
      "序号",
      "购买方名称",
      "货物或应税劳务名称",
      "单位",
      "单价",
      "orderNum",
      "jine",
      "plateNumber",
      "name",
      "phone",
      "time",
    ], //导出表头
  ]; // 表格表头
  orginData.value.forEach((item: any, index: number) => {
    let rowData = [];
    //导出内容的字段
    rowData = [
      index + 1,
      item.购买方名称,
      item.货物或应税劳务名称,
      item.单位,
      item.单价,
      item.orderNum,
      item.jine,
      item.plateNumber,
      item.name,
      item.phone,
      item.time,
    ];
    tableData.push(rowData);
  });
  let workSheet = XLSX.utils.aoa_to_sheet(tableData);
  let bookNew = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(bookNew, workSheet, "作品名称"); // 工作簿名称
  let currentTimestampInSeconds = Date.now();
  let name = "发货单" + currentTimestampInSeconds + ".xlsx";
  XLSX.writeFile(bookNew, name);
};
</script>

<style scoped></style>
